package logic

import (
	"context"
	"github.com/pkg/errors"
	"group-card/common/constant"
	"group-card/common/request"
	"group-card/model/entity"
	"group-card/rpc/card/cardclient"
	"group-card/rpc/card/internal/svc"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type PublishConfirmLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewPublishConfirmLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PublishConfirmLogic {
	return &PublishConfirmLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// region TODO: 确认发行 Author:LiuYanLin Date:2023/04/05 周三 11:01

func (l *PublishConfirmLogic) PublishConfirm(in *cardclient.PublishConfirmRequest) (*cardclient.PublishConfirmResponse, error) {
	var ctx context.Context

	//region TODO: 获取卡片发行记录详情 Author:LiuYanLin Date:2023/07/03 周一 13:42
	cardPublishResp, err := l.svcCtx.PublishModel.GetCardPublishJoin(ctx, &entity.CardPublishReq{
		Id: in.Id,
	})
	if err != nil {
		return nil, err
	}
	if cardPublishResp.Status != constant.CardPublishStatus10 {
		return nil, errors.New("请勿重复发行")
	}
	//endregion

	db := l.svcCtx.Orm.NewSession()
	db.Begin()
	defer db.Close()

	//region TODO: 修改卡片发行记录(事务) Author:LiuYanLin Date:2023/07/03 周一 13:53
	err = l.svcCtx.PublishModel.UpdateCardPublishDb(ctx, db, &entity.CardPublishReq{
		Id:          in.Id,
		PublishTime: time.Now(),
		Status:      constant.CardPublishStatus20,
		BaseReq: request.BaseReq{
			Columns: "publish_time,status,update_at",
		},
	})
	if err != nil {
		db.Rollback()
		return nil, err
	}
	//endregion

	//region TODO: 添加卡片绑定记录(事务) Author:LiuYanLin Date:2023/04/04 周二 17:31
	addCardBindingList := make([]*entity.CardBindingReq, 0)
	for i := cardPublishResp.BeginNumber; i <= cardPublishResp.EndNumber; i++ {
		addCardBindingList = append(addCardBindingList, &entity.CardBindingReq{
			CardNumber:    i,
			CustomerId:    cardPublishResp.CustomerId,
			FaceValue:     cardPublishResp.FaceValue,
			Balance:       float64(cardPublishResp.FaceValue),
			Status:        constant.CardBindingStatus10,
			ServiceNumber: cardPublishResp.ServiceNumber,
		})
	}
	err = l.svcCtx.BindingModel.AddCardBindingListDb(ctx, db, addCardBindingList)
	if err != nil {
		db.Rollback()
		return nil, err
	}
	//endregion

	db.Commit()

	return &cardclient.PublishConfirmResponse{}, nil
}

//endregion
